﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;

namespace Mota.EditModule
{
    public class ObjectPrototype
    {
        private Dictionary<string, SqlDbType> fields;
        private DataTable dataTable = null;
        private String viewName = String.Empty;
        private ObjectPrototype()
        {
        }
        public ObjectPrototype(XElement rootControlElement,string viewName)
        {
            // parse xml and add fields and types to dictionary
            fields = rootControlElement.Descendants("Properties")
                                                .Where(el => (el.Element("AttributeType") != null)
                                                            && (el.Element("XMLAttribute") != null))
                                                .Select(el => new KeyValuePair<string, SqlDbType>(el.Element("XMLAttribute").Value,
                                                                       (SqlDbType)Enum.Parse(typeof(SqlDbType),
                                                                            el.Element("AttributeType").Value)))
                                                .Distinct(new ComparerByKey())
                                                .ToDictionary(key => key.Key,
                                                              type => type.Value);
            this.viewName = viewName;
        }
        public int FieldsCount 
        { 
            get
            {
                return fields.Count;
            }
        }

        public DataTable GetCompatibleDataTable()
        {
            if (dataTable == null)
            {
                dataTable = new DataTable();
                dataTable.TableName = viewName;
                var columns = from column in fields
                              select new DataColumn(column.Key, column.Value.ToType());
                
                dataTable.Columns.AddRange(columns.ToArray());
            }
            return dataTable;
        }

    }
}
